package dir

import (
	"github.com/asdine/storm/v3"
	"sync"
)

type Operate struct {
	db   *storm.DB
	lock sync.Mutex
}

func NewOperate(db *storm.DB) *Operate {
	return &Operate{db: db}
}

func (o *Operate) Update(dir FileDir) error {
	return o.db.Update(&dir)
}

func (o *Operate) Set(dir FileDir) error {
	return o.db.Save(&dir)
}

func (o *Operate) Get(name string) (*FileDir, error) {
	var info FileDir
	err := o.db.One("Name", name, &info)
	if err != nil {
		if err == storm.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &info, nil
}

func (o *Operate) Delete(dir FileDir) error {
	return o.db.DeleteStruct(&dir)
}

func (o *Operate) List(pageNum, limit int) ([]FileDir, error) {
	offset := (pageNum - 1) * limit
	var info []FileDir
	err := o.db.All(&info, storm.Limit(limit), storm.Skip(offset), storm.Reverse())
	if err != nil {
		if err == storm.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	return info, nil
}

func (o *Operate) Count() (int, error) {
	return o.db.Count(&FileDir{})
}
